<template>
  <el-dialog
    v-el-drag-dialog
    title="新增计划充装单"
    :visible.sync="visible"
    width="1100px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-position="right" label-width="100px">
      <el-form-item label="仓库名称:" prop="storeId">
        <el-select v-model="temp.storeId" clearable placeholder="请选择" style="width: 100%;">
          <el-option
            v-for="item in storeMap"
            :key="item.storeId"
            :label="item.storeName"
            :value="item.storeId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注:" prop="remark">
        <el-input v-model="temp.remark" type="textarea" :rows="3" show-word-limit maxlength="100" />
      </el-form-item>
    </el-form>
    <el-row :gutter="10">
      <el-col :span="6">
        <lb-table
          ref="lbTableLeft"
          border
          class="leftTable"
          highlight-current-row
          element-loading-text="加载中"
          :column="tableLeftData.column"
          :data="tableLeftData.data"
          @current-change="tableLeftChange"
        />
      </el-col>
      <el-col :span="18">
        <lb-table
          ref="lbTableRight"
          border
          class="rightTable"
          element-loading-text="加载中"
          :column="tableRightData.column"
          :data="tableRightData.data"
        />
        <div class="total">充装总数：{{ totalCount }}</div>
      </el-col>
    </el-row>
    <!-- <div class="total">本次出库<span v-for="(item,index) in sumObj" v-show="item.sum" :key="index">{{ `${item.name}瓶小计${item.sum}，` }}</span>合计{{ allSum }}瓶</div> -->
    <div slot="footer" class="dialog-footer">
      <el-button @click="reset">
        关闭
      </el-button>
      <el-button :loading="loading" type="primary" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

  <script>
  import { plannedFillingOrderSave, goodsTypeQueryAllList, goodsSortList } from '@/api'
  import { formatColumnMap } from '@/utils'
  import { mapGetters } from 'vuex'

  export default {
    name: 'add',
    props: {
      storeMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        formatColumnMap,
        visible: false,
        type: 'add',
        temp: {
          storeId: '',
          remark: ''
        },
        totalCount: 0,
        rules: {
          storeId: [{ required: true, message: '请选择仓库', trigger: 'change' }]
        },
        loading: false,
        // 左侧列表
        tableLeftData: {
          column: [
            {
              prop: 'goodsName',
              label: '商品名称'
            },
            {
              prop: 'specName',
              label: '规格型号',
              width: 80
            }
          ],
          data: []
        },
        // 右侧列表
        tableRightData: {
          column: [
            {
              prop: 'goodsName',
              label: '商品名称',
              width: 160
            },
            {
              prop: 'goodsSpec',
              label: '规格型号'
            },
            {
              prop: 'gdCount',
              label: '数量',
              render: (h, scope) =>
                (scope.row._edit && scope.row['pricingMode'] === 1) ? (
                // <el-input
                //   style='width: 100px'
                //   maxlength={10}
                //   v-model={scope.row[scope.column.property]}
                //   onInput={(val) =>
                //     (scope.row[scope.column.property] = val
                //       .replace(/[^\d.]/g, '')
                //       .replace(/^0\d+|^\./g, '')
                //       .replace(/\.{2,}/g, '.')
                //       .replace('.', '$#$')
                //       .replace(/\./g, '')
                //       .replace('$#$', '.')
                //       .replace(/^(.*\..{2}).*$/, '$1'))
                //   }
                //   size='mini'
                // />
                <el-input-number v-model={scope.row[scope.column.property]} size='mini' min={1} max={1000} controls={false} ></el-input-number>
                  ) : (
                <span>{scope.row[scope.column.property]}</span>
              )
            },
            {
              label: '操作',
              width: '150px',
              fixed: 'right',
              render: (h, scope, $index) => {
                return (
                <div>
                  {scope.row._edit ? (
                    <div>
                      <el-link
                        type='primary'
                        underline={false}
                        size='mini'
                        onClick={() => this.handleSave(scope)}
                      >
                        保存
                      </el-link>
                      <el-link
                        type='primary'
                        underline={false}
                        size='mini'
                        onClick={() => this.handleDel(scope)}
                      >
                        删除
                      </el-link>
                    </div>
                  ) : (
                    <div>
                      <el-link
                        type='primary'
                        underline={false}
                        size='mini'
                        onClick={() => this.handleEdit(scope)}
                      >
                        编辑
                      </el-link>
                      <el-link
                        type='primary'
                        underline={false}
                        size='mini'
                        onClick={() => this.handleDel(scope)}
                      >
                        删除
                      </el-link>
                    </div>
                  )}
                </div>
                )
              }
            }
          ],
          data: [],
          defaultData: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'userInfo', 'corpSettingData'
      ])
    },
    methods: {
      open(temp) {
        this.getGoodsList()
        return new Promise(resolve => {
          this.resolve = resolve
          this.type = 'add'
          this.visible = true
          if (temp) {
            this.temp = Object.assign(this.temp, temp)
            this.type = 'edit'
          }
        })
      },
      tableLeftChange(row) {
        if (!row) {
          return
        }
        // console.log('row', row)
        const obj = {
          gtId: this.goodsData.gtId,
          gtSNNo: this.goodsData.gtSNNo,
          gtName: this.goodsData.gtName,
          goodsCode: row.goodsCode,
          goodsName: row.goodsName,
          goodsSpec: row.specName,
          specCode: row.specCode,
          unitId: row.unitId,
          unitName: row.unitName,
          tempGdStatus: row.gdStatus,
          goodsId: row.goodsId,
          gtFlag: this.goodsData.gtFlag,
          pricingMode: row.pricingMode,
          // gdStatus: '', // 状态
          gdCount: undefined, // 数量
          // netWeight: '', // 重量
          remark: '',
          _edit: true // 是否编辑
          // gdStatusMap: []
        }
        // 处理是已经增加过该商品
        var flag = []
        if (this.tableRightData.data.length) {
          flag = this.tableRightData.data.filter((item) => item.goodsId === obj.goodsId && item.gdStatus === obj.gdStatus)
        }
        if (flag.length) {
          this.$message({
            type: 'warning',
            message: `${obj.gtName}已存在`
          })
          return
        }
        console.log('obj', obj)
        // 为每行数据添加可供选择的状态
        // obj.gdStatusMap = this.setGdStatusMap(obj)
        // 把当前的数据放在右边列表
        this.tableRightData.data.push(obj)
        console.log('增加后的数据', this.tableRightData.data)
      },
      // 商品分类
      async getGoodsList() {
        const res = await goodsTypeQueryAllList()
        const item = res.data.find(item => item.gtFlag === 2)
        this.currentChange(item)
      },
      // 商品分类事件
      async currentChange(current) {
        this.goodsData = current
        const res = await goodsSortList({
          gtId: current.gtId,
          pageIndex: 1,
          pageSize: 999
        })
        if (this.corpSettingData.sp3 >> 6 & 0x01) {
          const list = res.data.rows.filter(item => {
            if (!item.options) {
              return true
            }
            if (item.options >> 1 & 0x01) {
              return false
            }
            if (item.options >> 2 & 0x01) {
              return false
            }
            return true
          })
          console.log('list', list)
          this.tableLeftData.data = list
        } else {
          this.tableLeftData.data = res.data.rows.filter(item => item.pricingMode === 1)
        }
      },
      handleEdit(scope) {
        console.log(scope)
        console.log(this.tableRightData.data[scope.$index])
        this.$set(scope.row, '_edit', true)
      },
      // 保存
      async handleSave(scope) {
        if (!scope.row.gdCount) {
          this.$message.warning('请完善商品信息')
          return
        }
        this.$set(scope.row, '_edit', false)
        this.$set(
          this.tableRightData.defaultData,
          scope.$index,
          JSON.parse(JSON.stringify(scope.row))
        )
        this.totalCount = 0
        this.tableRightData.defaultData.forEach(item => {
          if (item.pricingMode === 1) {
            this.totalCount += Number(item.gdCount)
          }
        })
      },
      handleDel(scope) {
        const row = this.tableRightData.data
        const defaultRow = this.tableRightData.defaultData
        this.$delete(row, scope.$index)
        this.$delete(defaultRow, scope.$index)
      },
      success() {
        this.$refs.dataForm.validate(async valid => {
          if (!valid) return
          if (!this.tableRightData.data.length) {
            this.$message({
              type: 'error',
              message: `请添加商品`
            })
            return
          }
          for (var i = 0; i < this.tableRightData.data.length; i++) {
            if (this.tableRightData.data[i]._edit) {
              this.$message({
                type: 'error',
                message: `请完成商品的编辑`
              })
              return
            }
            if (this.tableRightData.data[i].pricingMode === 1) {
              if (this.tableRightData.data[i].gdCount * 1 === 0) {
                this.$message({
                  type: 'warning',
                  message: `请输入${this.tableRightData.data[i].goodsName}数量`
                })
                return
              }
            }
          }
          this.add()
        })
      },
      async add() {
        this.loading = true
        const detailInfoList = this.tableRightData.data.map((item) => {
          return {
            goodsId: item.goodsId,
            gdCount: Number(item.gdCount)
          }
        })

        const storeInfo = this.storeMap.find((item) => {
          return item.storeId === this.temp.storeId
        })
        const storeName = storeInfo ? storeInfo.storeName : ''
        const params = {
          ...this.temp,
          storeName,
          detailInfoList
        }
        await plannedFillingOrderSave(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '新增成功',
          type: 'success',
          duration: 2000
        })
      },
      reset() {
        this.visible = false
        this.temp = {
          storeId: '',
          remark: ''
        }
        this.tableRightData.data = []
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
          this.loading = false
        })
      }
    }
  }
  </script>

  <style lang="scss" scoped>
    .form {
      display: flex;
      flex-wrap: wrap;
      width: 50%;
      & /deep/ .el-form-item {
        width: 100%;
      }
    }
    .total {
      margin-top: 10px;
      font-size: 16px;
      font-weight: 600;
      color: #F00;
    }
  </style>
